package repository.relsys.services.datacentral;

import org.apache.log4j.Logger;
import repository.relsys.app.*;

import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.sdb.SDBFactory;
import com.hp.hpl.jena.sdb.Store;
import com.hp.hpl.jena.sdb.StoreDesc;
import com.hp.hpl.jena.sdb.sql.JDBC;
import com.hp.hpl.jena.sdb.sql.SDBConnection;
import com.hp.hpl.jena.sdb.store.DatabaseType;
import com.hp.hpl.jena.sdb.store.LayoutType;

public class RepositoryDataProvider implements DataProvider {

	private Logger logger = Logger.getLogger(this.getClass().getName());

	private StoreDesc storeDesc;
	
	private SDBConnection conn;

	private Store store;


	public RepositoryDataProvider()
	{
	    String jdbcURL = Settings.getInstance().config.dbConfig.dbURL;
		String user = Settings.getInstance().config.dbConfig.dbUser;
		String pw = Settings.getInstance().config.dbConfig.dbPassword;

		// create a data store description for MYSQL database
		storeDesc = new StoreDesc(LayoutType.LayoutTripleNodesHash,
				DatabaseType.MySQL);
		// establish connection to database
		
		
		JDBC.loadDriverMySQL();
		
	    System.out.println("JDBC loaded");
		conn = new SDBConnection(jdbcURL, user, pw);
		store = SDBFactory.connectStore(conn, storeDesc);
	}


	public Model getData()
	{
		Model dataModel = null;

		try {
			
			if (Settings.getInstance().config.dbConfig.createTables) {				
				store.getTableFormatter().create();
			}
		
			dataModel = SDBFactory.connectDefaultModel(store);

		} catch (Exception e) {
			logger.error("Could not load DataModel from database!", e);
		}

		return dataModel;
	}

	
	public void updateDataSource(Model dataModel)
	{
		
		store.close();
		conn.close();
	}

}
